package com.zhongketech.sunflower.transport.uitl;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import com.zhongketech.sunflower.Constant;
import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.MyToast;
import com.zhongketech.sunflower.transport.HttpPatch;
import com.zhongketech.sunflower.transport.InterfaceUrls;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.model.ImageUrl;
import com.zhongketech.sunflower.transport.model.SmsCode;
import com.zhongketech.sunflower.transport.model.User;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Toast;




public class NetTransportUtil {

	private static String TAG = "NetTransportUtil";
	public static final String BaseUrl = "http://182.92.193.118/sunflower/v1/index.php/";//待确认
	private static String requestInterfaceUrl = null;


	/* 
	 * get数据
	 */
	public static String getContent(final String interfaceUrl,Map<String, String> params) {

		if(interfaceUrl == null){
			return null;
		}

		requestInterfaceUrl = interfaceUrl;
		String url = BaseUrl + interfaceUrl;
		if(null != params){

			Set set = params.entrySet();
			Iterator it = set.iterator();
			Map.Entry mapEntry = (Map.Entry) it.next();
			url = url+"?"+mapEntry.getKey()+"="+mapEntry.getValue();
			while (it.hasNext()) { // 遍历map中的每一项
				mapEntry = (Map.Entry) it.next();
				url = url+"&"+mapEntry.getKey()+"="+mapEntry.getValue();
			}

		}

		LogUtil.i(TAG, "get request url= "+url);
		HttpGet request = new HttpGet(url);
		return httpRequest(request);

	}

	/**
	 * post提交数据
	 * 
	 * @param interfaceUrl
	 *            提交地址
	 * @param params
	 *            参数
	 * @param encoding
	 *            参数编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getContentByPost(final String interfaceUrl,
			Map<String, String> params) {

		if(interfaceUrl == null){
			return null;
		}

		requestInterfaceUrl = interfaceUrl;
		String url = BaseUrl + interfaceUrl;
		LogUtil.i(TAG, "request url= "+url);

		//添加body
		ByteArrayEntity entity = null;
		if(null != params){
			String requestBody = "{";
			Set set = params.entrySet();
			Iterator it = set.iterator();
			Map.Entry mapEntry = (Map.Entry) it.next();
			requestBody = requestBody+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			while (it.hasNext()) { // 遍历map中的每一项
				mapEntry = (Map.Entry) it.next();
				requestBody = requestBody+","+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			}
			requestBody = requestBody+"}";
			LogUtil.i(TAG, "requestBody:"+requestBody);
			try {
				entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
				entity.setContentType("application/json");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		HttpPost request = new HttpPost(url);
		if(null != entity) 
		{

			request.setEntity(entity);
		}

		return httpRequest(request);
	}
	
	
	public static String getContentByPatch(final String interfaceUrl,
			Map<String, String> params) {

		if(interfaceUrl == null){
			return null;
		}

		requestInterfaceUrl = interfaceUrl;
		String url = BaseUrl + interfaceUrl;
		LogUtil.i(TAG, "request url= "+url);

		//添加body
		ByteArrayEntity entity = null;
		if(null != params){
			String requestBody = "{";
			Set set = params.entrySet();
			Iterator it = set.iterator();
			Map.Entry mapEntry = (Map.Entry) it.next();
			requestBody = requestBody+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			while (it.hasNext()) { // 遍历map中的每一项
				mapEntry = (Map.Entry) it.next();
				requestBody = requestBody+","+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			}
			requestBody = requestBody+"}";
			LogUtil.i(TAG, "requestBody:"+requestBody);
			try {
				entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
				entity.setContentType("application/json");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		HttpPatch request = new HttpPatch(url);
		if(null != entity) 
		{

			request.setEntity(entity);
		}

		return httpRequest(request);
	}



	/**
	 * PUT提交数据
	 * 
	 * @param interfaceUrl
	 *            提交地址
	 * @param params
	 *            参数
	 * @param encoding
	 *            参数编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getContentByPut(final String interfaceUrl,
			Map<String, String> params) {

		if(interfaceUrl == null){
			return null;
		}

		requestInterfaceUrl = interfaceUrl;
		String url = BaseUrl + interfaceUrl;
		LogUtil.i(TAG, "request url= "+url);

		//添加body
		ByteArrayEntity entity = null;
		if(null != params){
			String requestBody = "{";
			Set set = params.entrySet();
			Iterator it = set.iterator();
			Map.Entry mapEntry = (Map.Entry) it.next();
			requestBody = requestBody+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			while (it.hasNext()) { // 遍历map中的每一项
				mapEntry = (Map.Entry) it.next();
				requestBody = requestBody+","+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			}
			requestBody = requestBody+"}";
			LogUtil.i(TAG, "requestBody:"+requestBody);
			try {
				entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
				entity.setContentType("application/json");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		HttpPut request = new HttpPut(url);
		if(null != entity) 
		{

			request.setEntity(entity);
		}

		return httpRequest(request);
	}

	public class myInputStream extends InputStream
	{

		@Override
		public int read() throws IOException {
			// TODO Auto-generated method stub
			return 0;
		}

	}

	public static String getFileName(String filePath) {
		if (TextUtils.isEmpty(filePath)) {
			return null;
		}
		int index = filePath.lastIndexOf("/");
		String bitmapName = filePath.substring(index + 1);
		//        String prefixName = filePath.substring(0, index);
		//        prefixName = prefixName.replace(".", "");
		//        prefixName = prefixName.replace("/", "");
		//        prefixName = prefixName.replace(":", "");
		//        String fullName = prefixName + bitmapName;
		LogUtil.i("ZK", "bitmapName :"+bitmapName);
		return bitmapName;
	}

	public static ImageUrl uploadimage(String actionUrl,String uploadFile)
	{
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = UUID.randomUUID().toString();
		String request = null;
		ImageUrl imageUrl = null;

		LogUtil.i("ZK", "actionUrl:"+actionUrl+" uploadFile:"+uploadFile);

		try
		{
			URL url =new URL(actionUrl);
			HttpURLConnection con=(HttpURLConnection)url.openConnection();
			CookieStore cookieStore = MyApplication.getInstance().getCookieStore();
			String PHPSESSID = null;
			String id = null;
			for(int i = 0;i < cookieStore.getCookies().size();i ++)
			{
				LogUtil.i("ZK", "Cookie:"+cookieStore.getCookies().get(i).getName()+"="+cookieStore.getCookies().get(i).getValue());

				if("PHPSESSID".equals(cookieStore.getCookies().get(i).getName()))
				{
					PHPSESSID = "PHPSESSID="+cookieStore.getCookies().get(i).getValue();
				}
				if("id".equals(cookieStore.getCookies().get(i).getName()))
				{
					id = "id="+cookieStore.getCookies().get(i).getValue();
				}
			}

			LogUtil.i("ZK", "Cookie:"+PHPSESSID+";"+id);

			/* 允许Input、Output，不使用Cache */
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Cookie", PHPSESSID+";"+id);
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary="+boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = 
					new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " +
					"name=\"images\";filename=\"" +
					getFileName(uploadFile) +"\"" + end);
			ds.writeBytes(end);   

			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(uploadFile);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			long count = 0;
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while((length = fStream.read(buffer)) != -1)
			{
				/* 将资料写入DataOutputStream中 */
				count = count +length;
				ds.write(buffer, 0, length);
			}
			LogUtil.i("ZK", "fStream count:"+count/1024+"KB");
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

			/* close streams */
			fStream.close();
			ds.flush();

			//			/* 取得Response内容 */
			//			InputStream is = con.getInputStream();
			//			int ch;
			//			StringBuffer b =new StringBuffer();
			//			while( ( ch = is.read() ) != -1 )
			//			{
			//				b.append( (char)ch );
			//			}
			//			/* 将Response显示于Dialog */
			//			MyToast.getInstance().show("上传成功"+b.toString().trim());
			//			/* 关闭DataOutputStream */
			int responseCode = con.getResponseCode();
			LogUtil.i(TAG, "httpRequest getStatusCode   ="+responseCode);
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b =new StringBuffer();
			while( ( ch = is.read() ) != -1 )
			{
				b.append( (char)ch );
			}
			LogUtil.i(TAG, "httpRequest b= "+b);
			request = DataUtils.decodeUnicode(b.toString());
			LogUtil.i(TAG, "httpRequest result= "+request);
			ds.close();

			if (responseCode == HttpStatus.SC_OK ) {
				Gson gson = new Gson();
				imageUrl = gson.fromJson(request, ImageUrl.class);
				return imageUrl;
			}
			else if(responseCode == HttpStatus.SC_INTERNAL_SERVER_ERROR)
			{
				MyToast.getInstance().show(request);
				return imageUrl;
			}
			else if(responseCode == HttpStatus.SC_NOT_IMPLEMENTED)
			{
				MyToast.getInstance().show("未登录");
				return imageUrl;
			}


		}
		catch(Exception e)
		{
			MyToast.getInstance().show("上传失败"+e);
		}

		return imageUrl;
	}


	private static String httpRequest(HttpUriRequest request)
	{
		//		Map<String, String> cookieMap = MyApplication.getInstance().getCookie();
		//		if(null != cookieMap && !requestInterfaceUrl.equals(InterfaceUrls.authorizations))
		//		{	
		//			String PHPSESSID = cookieMap.get(Constant.PREFS_COOKIE_PHPSESSID);
		//			if(null != PHPSESSID && PHPSESSID.length() > 5)
		//			{
		//				LogUtil.i(TAG, "set headers:"+PHPSESSID);
		//				request.setHeader("Set-Cookie", Constant.PREFS_COOKIE_PHPSESSID+"=" + PHPSESSID);	
		////				request.setHeader("Cookie", Constant.PREFS_COOKIE_ID+"=" + cookieMap.get(Constant.PREFS_COOKIE_ID));
		//			}
		//		}

		HttpClient httpClient = CustomerHttpClient.getHttpClient();
		LogUtil.i(TAG, "httpclient"+httpClient);
		if(!requestInterfaceUrl.equals(InterfaceUrls.authorizations))
		{

			CookieStore cookieStore = MyApplication.getInstance().getCookieStore();
			if(LogUtil.LogON)
			{
				for(int i = 0;null != cookieStore && i < cookieStore.getCookies().size();i ++)
				{
					LogUtil.i(TAG, "set cookie["+i+"]"+cookieStore.getCookies().get(i).getName()+":"+cookieStore.getCookies().get(i).getValue());
				}
			}
			((AbstractHttpClient) httpClient).setCookieStore(cookieStore);
		}
		//		Header[] headers  = request.getAllHeaders();
		//		if(LogUtil.LogON)
		//		{
		//			for(int i = 0;i < headers.length;i ++)
		//			{
		//				LogUtil.i(TAG, "request headers["+i+"]"+headers[i].getName()+":"+headers[i].getValue());
		//			}
		//		}

		try {
			HttpResponse response = httpClient.execute(request);		
			//			CookieStore mCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
			//	        List<Cookie> cookie = mCookieStore.getCookies();
			//			if(null != cookie && requestInterfaceUrl.equals(InterfaceUrls.authorizations))
			//			{
			//				for(int i = 0;i < cookie.size(); i ++){
			//					if(Constant.PREFS_COOKIE_PHPSESSID.equals(cookie.get(i).getName()))
			//					{
			//						MyApplication.getInstance().setCookie(cookie);
			//					}
			//				}
			//			}

			if(requestInterfaceUrl.equals(InterfaceUrls.authorizations))
			{	
				//				if(LogUtil.LogON)
				//				{
				//					CookieStore cookieStore = ((AbstractHttpClient) httpClient)
				//	                        .getCookieStore();
				//					for(int i = 0;i < cookieStore.getCookies().size();i ++)
				//					{
				//						LogUtil.i(TAG, "save cookie["+i+"]"+cookieStore.getCookies().get(i).getName()+":"+cookieStore.getCookies().get(i).getValue());
				//					}
				//				}

				MyApplication.getInstance().setCookieStore(((AbstractHttpClient) httpClient)
						.getCookieStore());
			}
			//			

			//			headers  = response.getAllHeaders();
			//			if(LogUtil.LogON)
			//			{
			//				for(int i = 0;i < headers.length;i ++)
			//				{
			//					LogUtil.i(TAG, "response headers["+i+"]"+headers[i].getName()+":"+headers[i].getValue());
			//				}
			//			}

			LogUtil.i(TAG, "httpRequest getStatusCode   ="+response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ) {
				byte[] resBytes = EntityUtils.toByteArray(response.getEntity());
				String result = DataUtils.decodeUnicode(new String(resBytes));
				LogUtil.i(TAG, "httpRequest result= "+result);
				return result;
			}
			else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR)
			{
				byte[] resBytes = EntityUtils.toByteArray(response.getEntity());
				String result = DataUtils.decodeUnicode(new String(resBytes));
				LogUtil.i(TAG, "httpRequest result= "+result);
				MyToast.getInstance().show(result);
			}

		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}


		return null;
	}
}